package com.gkj.controller;

import com.gkj.blog.util.SessionUtil;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class KaptchaController {
    private static final Logger LOG = LoggerFactory.getLogger(KaptchaController.class);
    @Autowired
    private Producer captchaProducer;

    @GetMapping("/api/getAuthCode")
    public void getKaptcha(HttpServletResponse response) {
        ServletOutputStream out=null;
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpg");
            String authCode=captchaProducer.createText();
            SessionUtil.setKaptcha(authCode);
            BufferedImage kaptcha = captchaProducer.createImage(authCode);
            out = response.getOutputStream();
            ImageIO.write(kaptcha, "jpg", out);
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("获取验证码异常：{}", e.getMessage());
        }
    }

}
